import React, { useReducer } from "react";

// 定义state的初始值
const defaultState = {
  count: 10,
  name: "zhangsan",
};

// 定义reducer的函数，用于改变state的值
// action就是一个带有type属性的一个对象
const reducer = (state, action) => {
  switch (action.type) {
    case "add":
      return {
        ...state,
        count: state.count + 1,
      };
    case "minus":
      return {
        ...state,
        count: state.count - 1,
      };
    default:
      return state;
  }
};

const App = () => {
  const [state, dispatch] = useReducer(reducer, defaultState);

  const fn = () => {
    dispatch({
      type: "add",
    });
  };

  return (
    <>
      <h2>useReducer</h2>
      <p>count: {state.count}</p>
      <p>name: {state.name}</p>
      <button onClick={fn}>btn</button>
    </>
  );
};

export default App;
